package com.xinghen.common.zookeeper.generator.impl;

import com.xinghen.common.base.GlobalConstant;
import com.xinghen.common.zookeeper.generator.IdGenerator;
import com.xinghen.common.zookeeper.registry.base.RegistryCenter;
import com.xinghen.common.zookeeper.registry.base.RegistryInfo;

/**
 * @author xinghen
 * @ClassName: IncrementIdGenerator
 * @Package: com.xinghen.common.zookeeper.generator.impl
 * @Description 自增ID生成器
 * @create 2018-04-12 10:40
 */
public class IncrementIdGenerator implements IdGenerator {

    private static Long serviceId;

    private RegistryInfo registryInfo;

    public IncrementIdGenerator(RegistryInfo registryInfo) {
        this.registryInfo = registryInfo;
    }

    /**
     * 获取自增ID并保存到zookeeper中
     *
     * @return
     */
    @Override
    public Long nextId() {
        String app = registryInfo.getApp();
        String host = registryInfo.getHost();
        RegistryCenter registryCenter = registryInfo.getRegistryCenter();
        String path = GlobalConstant.Zookeeper.REGISTRY_ID_ROOT_PATH + GlobalConstant.Symbol.SLASH + app
                + GlobalConstant.Symbol.SLASH + host;
        if (registryCenter.exists(path)) {
            // 如果已经有该节点，表示已经为当前的host上部署的该app分配的编号（应对某个服务重启之后编号不变的问题），直接获取该id，而无需生成
            return Long.valueOf(registryCenter.getDirectly(path));
        } else {
            //节点不存在，那么需要生成id，利用zk节点的版本号每写一次就自增的机制来实现
            registryCenter.increment(GlobalConstant.Zookeeper.ZK_REGISTRY_SEQ, 2000, 3);
            Integer id = registryCenter.getAtomicValue(GlobalConstant.Zookeeper.ZK_REGISTRY_SEQ, 2000, 3)
                    .postValue();
            registryCenter.persist(path, String.valueOf(id));
            return Long.valueOf(id);
        }
    }

    public static Long getServiceId() {
        return serviceId;
    }

    public static void setServiceId(Long serviceId) {
        IncrementIdGenerator.serviceId = serviceId;
    }
}
